package cmpe451.group7.ourcity.beans;

import java.io.ByteArrayInputStream;
import java.io.IOException;

import javax.faces.bean.ApplicationScoped;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseId;

import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;

import cmpe451.group7.ourcity.dao.MultimediaDAO;
import cmpe451.group7.ourcity.entity.Multimedia;

/**
 * This bean is used to connect to the webserver and convert the image to a
 * format that JSF can understand
 */
@ManagedBean
@ApplicationScoped
public class PlaceImageBean {

	@ManagedProperty(value = "#{multimediaDAO}")
	private MultimediaDAO multimediaDAO;

	public StreamedContent getImage() throws IOException {
		FacesContext context = FacesContext.getCurrentInstance();

		if (context.getCurrentPhaseId() == PhaseId.RENDER_RESPONSE) {
			// So, we're rendering the view. Return a stub StreamedContent so
			// that it will generate right URL.
			return new DefaultStreamedContent();
		} else {
			// So, browser is requesting the image. Return a real
			// StreamedContent with the image bytes.
			String idText = context.getExternalContext()
					.getRequestParameterMap().get("id");
			int id = Integer.parseInt(idText);
			Multimedia image = multimediaDAO.findByID(id);
			return new DefaultStreamedContent(new ByteArrayInputStream(
					image.getFile()), image.getMimeType());
		}
	}

	public MultimediaDAO getMultimediaDAO() {
		return multimediaDAO;
	}

	public void setMultimediaDAO(MultimediaDAO multimediaDAO) {
		this.multimediaDAO = multimediaDAO;
	}

}
